package com.abe.bathsystem.android.v3;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.abe.bathsystem.android.service.FlowWindowService;
import com.abe.bathsystem.base.ManagerLocalData;
import com.abe.bathsystem.base.ManagerTimer;
import com.abe.bathsystem.entity.http.HttpVersionEntity;
import com.abe.bathsystem.utils.ConstantBath;
import com.abe.bathsystem.utils.NormalUtils;
import com.abe.bathsystem.widget.button.LongTouchBtn;
import com.abe.bathsystem.widget.dialog.ChooseLogDialog;
import com.abe.bathsystem.widget.dialog.ChooseMenuDialog;
import com.abe.bathsystem.widget.dialog.DialogContract;
import com.abe.bathsystem.widget.dialog.SerialPortDialog;
import com.abe.bathsystem.widget.dialog.SerialSetPosAddDialog;
import com.abe.bathsystem.widget.dialog.SerialSetPosDialog;
import com.abe.bathsystem.widget.dialog.SettingAppsDialog;
import com.abe.bathsystem.widget.dialog.SettingDialog;
import com.abe.bathsystem.widget.dialog.SettingUrlDialog;
import com.abe.bathsystem.widget.dialog.SupportLimitBathDialog;
import com.abe.bathsystem.widget.dialog.SupportLockerDialog;
import com.abe.bathsystem.widget.dialog.VersionDialog;
import com.abe.libcore.utils.normal.CommonUtils;
import com.abe.libcore.utils.normal.ConstantCore;
import com.abe.libcore.utils.normal.FileDownloadUtils;
import com.abe.libcore.utils.normal.FileUtils;
import com.abe.libcore.utils.normal.ThreadPoolUtils;

import net.yet.campusdev.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;

public abstract class MainBathSetActivity extends MainBathAbsActivity implements DialogContract.OnSerialPortSetAddressListener {

    protected abstract void resetSerialPort();

    protected ChooseMenuDialog menuDialog;
    protected SerialPortDialog serialPortDialog;
    protected SettingDialog settingDialog;
    protected SettingUrlDialog settingUrlDialog;
    protected SupportLockerDialog lockerDialog;
    protected SupportLimitBathDialog limitBathDialog;
    protected SerialSetPosDialog setPosDialog;
    protected SerialSetPosAddDialog setPosAddDialog;
    protected SettingAppsDialog settingAppsDialog;
    protected ChooseLogDialog chooseLogDialog;

    @Override
    protected void dismissDialog() {
        super.dismissDialog();
        //dismissDialog(menuDialog);
        //dismissDialog(serialPortDialog);
        //dismissDialog(settingDialog);
        //dismissDialog(settingUrlDialog);
        //dismissDialog(lockerDialog);
        //dismissDialog(setPosDialog);
        //dismissDialog(setPosAddDialog);
    }

    private static final int SetChange = 0x009;
    private static final int ShowUploadLogDialog = 0x010;

    class BaseHandler extends Handler {
        BaseHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SetChange: {
                    showSetParam();
                }
                break;
                case ShowUploadLogDialog: {
                    List<String> fileNames = msg.getData().getStringArrayList("log");
                    final String type = msg.getData().getString("type", TYPE_PUSH_LOG);
                    if (fileNames == null || fileNames.size() == 0) {
                        localSendMessage(APP_TOAST, "暂无日志 ");
                    }
                    chooseLogDialog = new ChooseLogDialog(MainBathSetActivity.this, MainBathSetActivity.this, fileNames);
                    chooseLogDialog.setListener(new DialogContract.OnChooseFileListener() {
                        @Override
                        public void onChooseLog(String fileName) {
                            chooseLogDialog.dismiss();
                            String dir = ConstantCore.LOG_HTTP_PATH;
                            switch (type) {
                                case TYPE_HTTP_LOG:
                                    dir = ConstantCore.LOG_HTTP_PATH;
                                    break;
                                case TYPE_PUSH_LOG:
                                    dir = ConstantBath.LOG_PUSH_XG_PATH;
                                    break;
                                case TYPE_SERIAL_LOG:
                                    dir = ConstantCore.LOG_SERIAL_PATH;
                                    break;
                            }
                            String fullName = dir + File.separator + fileName;
                            uploadPresenter().uploadLog(fullName);
                        }
                    });
                    chooseLogDialog.show();
                }
                break;
            }
        }
    }

    @Override
    public void initContent() {
        super.initContent();
        itemBtnSetting.setOnLongTouchListener(new LongTouchBtn.LongTouchListener() {
            @Override
            public void onStartTouch() {

            }

            @Override
            public void onLongTouch() {
                settingDialog = new SettingDialog(MainBathSetActivity.this, MainBathSetActivity.this);
                settingDialog.setListener(new DialogContract.OnSettingCheckListener() {
                    @Override
                    public void onCheckSuccess(boolean isSuccess) {
                        itemSettingRootView.setVisibility(isSuccess ? View.VISIBLE : View.GONE);
                    }
                });
                settingDialog.show();
            }

            @Override
            public void onEndTouch() {

            }
        }, 2 * 1000);
        showSetParam();
    }

    private void showSetParam() {
        itemCheckVersion.setText(NormalUtils.getVersionName());
        String lockTime = ManagerTimer.format(ManagerTimer.autoLockTime());
        itemLockTime.setText(lockTime);
        String adTime = ManagerTimer.format(ManagerTimer.adUpdateTime());
        itemAdTime.setText(adTime);
        itemSerialPort.setText(ManagerLocalData.getSerialPort());
        itemServiceUrl.setText(ManagerLocalData.getServiceUrl());
        itemLocker.setText(ManagerLocalData.isSupportLocker() ? "支持" : "不支持");
        itemLimitBath.setText(ManagerLocalData.isSupportLimitBath() ? "是" : "否");
        itemDeviceMac.setText(NormalUtils.getMac(this, false));
    }

    private void downloadApk(final String apkName, String url) {
        FileDownloadUtils.get().download(url, "abeframe", apkName, new FileDownloadUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                localSendMessage(APP_TOAST, "下载成功");
                boolean isInstall = NormalUtils.installAPK(ConstantCore.FILE_ROOT_PATH + File.separator + apkName);
                if (!isInstall) {
                    localSendMessage(APP_TOAST, "安装路径错误");
                }
            }

            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadFailed() {
                localSendMessage(APP_TOAST, "下载失败");
            }
        });
    }

    @Override
    public void onCheckVersion(boolean isSuccess, boolean isAutoUpdate, final HttpVersionEntity versionEntity) {
        if (isSuccess) {
            int versionCode = NormalUtils.getVersionCode();
            if (versionCode < versionEntity.getVersionCode()) {
                final String apkName = "bath-" + versionEntity.getVersionName() + ".apk";
                if (isAutoUpdate) {
                    String url = ConstantBath.AppDownUrl + versionEntity.getResId();
                    downloadApk(apkName, url);
                }
                VersionDialog dialog = new VersionDialog(MainBathSetActivity.this, versionEntity);
                dialog.setListener(new DialogContract.OnUpdateListener() {
                    @Override
                    public void onUpdate(boolean isUpdate, String url) {
                        if (isUpdate) {
                            downloadApk(apkName, url);
                        }
                    }
                });
                dialog.show();
            } else {
                localSendMessage(APP_TOAST, "当前版本为最新版本");
            }
        }
    }

    @Override
    public void onUploadLog(boolean isSuccess, int resId, String msg) {
        if (isSuccess) {
            CommonUtils.w("上传成功,resId:" + resId);
            uploadPresenter().saveLogData(String.valueOf(resId));
        } else {
            localSendMessage(APP_TOAST, msg);
        }
    }

    @Override
    public void onSaveLog(boolean isSuccess, String message) {
        localSendMessage(APP_TOAST, isSuccess ? "上传日志成功" : message);
    }

    class loadLog implements Runnable {

        private String type;

        loadLog(String type) {
            this.type = type;
        }

        @Override
        public void run() {
            String dir = ConstantCore.LOG_HTTP_PATH;
            switch (type) {
                case TYPE_HTTP_LOG:
                    dir = ConstantCore.LOG_HTTP_PATH;
                    break;
                case TYPE_PUSH_LOG:
                    dir = ConstantBath.LOG_PUSH_XG_PATH;
                    break;
                case TYPE_SERIAL_LOG:
                    dir = ConstantCore.LOG_SERIAL_PATH;
                    break;
            }
            ArrayList<String> fileNames = new ArrayList<>();
            if (!FileUtils.fileIsExists(dir)) {
                localSendMessage(APP_TOAST, "暂无日志");
                return;
            }
            File file = new File(dir);
            File[] subFile = file.listFiles();
            if (subFile == null || subFile.length == 0) {
                localSendMessage(APP_TOAST, "暂无日志");
                return;
            }
            for (File tempFile : subFile) {
                // 判断是否为文件夹
                if (!tempFile.isDirectory()) {
                    String filename = tempFile.getName();
                    fileNames.add(filename);
                }
            }
            Bundle bundle = new Bundle();
            bundle.putStringArrayList("log", fileNames);
            bundle.putString("type", type);
            Message msg = new Message();
            msg.what = ShowUploadLogDialog;
            msg.setData(bundle);
            new BaseHandler(Looper.getMainLooper()).sendMessage(msg);
        }
    }

    private final String TYPE_HTTP_LOG = "http", TYPE_SERIAL_LOG = "serial", TYPE_PUSH_LOG = "push";

    @OnClick({R.id.item_setting_root_view, R.id.item_show_serial_view,
            R.id.item_back_img, R.id.item_back_txt, R.id.item_btn_reset,
            R.id.item_btn_android_setting, R.id.item_android_apps,
            R.id.item_ad_time_layout, R.id.item_lock_time_layout,
            R.id.item_serial_port_layout, R.id.item_service_url_layout,
            R.id.item_locker_layout, R.id.item_serial_test_layout,
            R.id.item_check_version_layout, R.id.item_serial_set_add_layout,
            R.id.item_log_upload_layout, R.id.item_log_upload_socket_layout,
            R.id.item_log_upload_http_layout, R.id.item_limit_bath_layout})
    public void onSettingViewClicked(View view) {
        switch (view.getId()) {
            case R.id.item_limit_bath_layout: {
                limitBathDialog = new SupportLimitBathDialog(this, this);
                limitBathDialog.setListener(new DialogContract.OnSupportLimitBathListener() {
                    @Override
                    public void onSupportLimitBath(boolean isSupport) {
                        ManagerLocalData.setIsSupportLimitBath(isSupport);
                        new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(SetChange);
                    }
                });
                limitBathDialog.show();
            }
            break;
            case R.id.item_log_upload_http_layout:
                ThreadPoolUtils.execute(new loadLog(TYPE_HTTP_LOG));
                break;
            case R.id.item_log_upload_socket_layout:
                ThreadPoolUtils.execute(new loadLog(TYPE_SERIAL_LOG));
                break;
            case R.id.item_log_upload_layout:
                ThreadPoolUtils.execute(new loadLog(TYPE_PUSH_LOG));
                break;
            case R.id.item_btn_android_setting:
                //startActivity(new Intent(Settings.ACTION_SETTINGS));
                //打开悬浮窗
                //startService(new Intent(MainBathSetActivity.this, FlowWindowService.class));
                break;
            case R.id.item_android_apps:
                settingAppsDialog = new SettingAppsDialog(this, this);
                settingAppsDialog.setListener(new SettingAppsDialog.OnGotoSettingAppListener() {
                    @Override
                    public void onGoto(ResolveInfo info) {
                        //* 该应用的包名 */
                        String pkg = info.activityInfo.packageName;
                        //* 应用的主activity类 */
                        String cls = info.activityInfo.name;
                        ComponentName componet = new ComponentName(pkg, cls);
                        Intent i = new Intent();
                        i.setComponent(componet);
                        startActivity(i);
                        //打开悬浮窗
                        startService(new Intent(MainBathSetActivity.this, FlowWindowService.class));
                    }
                });
                settingAppsDialog.show();
                break;
            case R.id.item_setting_root_view:
                break;
            case R.id.item_check_version_layout:
                versionPresenter().checkVersion(false);
                break;
            case R.id.item_show_serial_view:
                break;
            case R.id.item_back_img:
                itemSettingRootView.setVisibility(View.GONE);
                break;
            case R.id.item_back_txt:
                itemSettingRootView.setVisibility(View.GONE);
                break;
            case R.id.item_btn_reset:
                NormalUtils.resetApp();
                break;
            case R.id.item_ad_time_layout:
                menuDialog = new ChooseMenuDialog(this, this, ChooseMenuDialog.TYPE_AD_UPDATE);
                menuDialog.setListener(new ChooseMenuDialog.OnChooseMenuListener() {
                    @Override
                    public void onChoose(int type, String data) {
                        if (type == ChooseMenuDialog.TYPE_AD_UPDATE && !TextUtils.isEmpty(data)) {
                            ManagerTimer.setAdUpdateTime(ManagerTimer.parse(data));
                            new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(SetChange);
                        }
                    }
                });
                menuDialog.show();
                break;
            case R.id.item_lock_time_layout:
                menuDialog = new ChooseMenuDialog(this, this, ChooseMenuDialog.TYPE_AUTO_LOCK);
                menuDialog.setListener(new ChooseMenuDialog.OnChooseMenuListener() {
                    @Override
                    public void onChoose(int type, String data) {
                        if (type == ChooseMenuDialog.TYPE_AUTO_LOCK && !TextUtils.isEmpty(data)) {
                            ManagerTimer.setAutoLockTime(ManagerTimer.parse(data));
                            new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(SetChange);
                        }
                    }
                });
                menuDialog.show();
                break;
            case R.id.item_serial_port_layout:
                serialPortDialog = new SerialPortDialog(this, this);
                serialPortDialog.setListener(new DialogContract.OnSetSerialPortListener() {
                    @Override
                    public void onSetSerialPort(String serialPortName) {
                        String oldSerialPort = ManagerLocalData.getSerialPort();
                        if (!oldSerialPort.equals(serialPortName)) {
                            ManagerLocalData.saveSerialPort(serialPortName);
                            new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(SetChange);
                            //重启串口
                            resetSerialPort();
                        }
                    }
                });
                serialPortDialog.show();
                break;
            case R.id.item_service_url_layout: {
                settingUrlDialog = new SettingUrlDialog(this, this);
                settingUrlDialog.setListener(new DialogContract.OnSetServiceUrlListener() {
                    @Override
                    public void onSetUrl(String url) {
                        ManagerLocalData.setServiceUrl(url);
                        new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(SetChange);
                    }
                });
                settingUrlDialog.show();
            }
            break;
            case R.id.item_locker_layout: {
                lockerDialog = new SupportLockerDialog(this, this);
                lockerDialog.setListener(new DialogContract.OnSupportLockerListener() {
                    @Override
                    public void onSupportLocker(boolean isSupport) {
                        ManagerLocalData.setIsSupportLocker(isSupport);
                        new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(SetChange);
                    }
                });
                lockerDialog.show();
            }
            break;
            case R.id.item_serial_test_layout: {
                setPosDialog = new SerialSetPosDialog(this, this);
                setPosDialog.setListener(new DialogContract.OnSetTestSerialPosListener() {
                    @Override
                    public void onSetEnd() {
                        itemSettingRootView.setVisibility(View.GONE);
                        itemShowSerialView.setVisibility(View.VISIBLE);
                    }
                });
                setPosDialog.show();
            }
            break;
            case R.id.item_serial_set_add_layout: {
                setPosAddDialog = new SerialSetPosAddDialog(this, this);
                setPosAddDialog.setListener(this);
                setPosAddDialog.show();
            }
            break;
        }
    }
}